package fr.uvsq.isty.bdh.hchess.gui.menu;

import fr.uvsq.isty.bdh.hchess.engine.GameData;
import fr.uvsq.isty.bdh.hchess.gui.game.GameDisplay;
import fr.uvsq.isty.bdh.hchess.gui.MainWindow;
import fr.uvsq.isty.bdh.hchess.interfacing.IChessPlayer;
import ictk.boardgame.chess.ChessGame;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 * The solo menu, where the user can choose the two opponent and start a new game.
 * 
 * @author Nathan Ramoly
 * @version 06-06-12
 */
public class SoloMenu extends JPanel{
	
    //Attributes

    /**
     * The parent windows
     */
    private MainWindow MW;

    /**
     * The Background picture
     */
    private Image bg;

    /**
     * The button to start
     */
    private JButton start;
    /**
     * The button to go back to the menu.
     */
    private JButton back;

    /**
     * Bottom panel, where the back and start button are.
     */
    private JEmptyPanel bottom;

    /**
     * Centered Panel
     */
    private PlayersSelectPannel playersSelectPannel;

    private JEmptyPanel mainCenterPanel;
    private JButton choosePGN;
    private JFileChooser fileChooser;
    private File PGNFile;
    
    private ChessGame gameToStart;


    //Methods
    /**
     * See SoloMenu(MainWindow parent, ChessGame toStart) with toStart==null;
     */
    public SoloMenu(MainWindow parent){
        this(parent,null);
    }
    /**
     * Constructor
     * @param parent the parent window containing this Panel. To be able to change
     * the content.
     * @param toStart The game to start. If null, the PGN loading button will be
     * displayed, and if no game is selected, the default game will be started.
     */
    public SoloMenu(MainWindow parent, ChessGame toStart)
    {
        this.MW = parent;
        this.gameToStart = toStart;
        this.setPreferredSize(new Dimension(GameDisplay.DEFAULT_WIDTH, GameDisplay.DEFAULT_HEIGHT));

        this.setLayout(new BorderLayout());

        //Background
        try {
            bg = ImageIO.read(getClass().getClassLoader()
                                .getResource("menu/menu.jpg"));
        } catch (IOException e1) {}


        //Bottom buttons (back & start)
        bottom = new JEmptyPanel();

        //Button Back
        back = new JButton("Back");		

        bottom.add(back, BorderLayout.PAGE_START);

        back.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                MW.setContentPane(new MainMenu(MW));
                MW.setVisible(true);
                MW.repaint();
            }
            });

        //Button Start
        start = new JButton("Start");	

        bottom.add(start, BorderLayout.PAGE_END);

        start.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onStartButtonPress();
            }
        });

        //Bottom area
        this.add(bottom, BorderLayout.PAGE_END);


        //Left area

        this.add(new JEmptyPanel(), BorderLayout.WEST);

        //Right area

        this.add(new JEmptyPanel(), BorderLayout.EAST);

        //top area
        JEmptyPanel top = new JEmptyPanel();
        top.setPreferredSize(new Dimension(100, 150) );

        this.add(top, BorderLayout.NORTH);



        ///center area
        playersSelectPannel = new PlayersSelectPannel(MW);


        mainCenterPanel = new JEmptyPanel();
        mainCenterPanel.setLayout(new BorderLayout());
        choosePGN = new JButton("Choose a PGN file...");

        mainCenterPanel.add(playersSelectPannel, BorderLayout.CENTER);
        mainCenterPanel.add(choosePGN, BorderLayout.SOUTH);


        this.add(mainCenterPanel, BorderLayout.CENTER);

        ///end center Area
        if(gameToStart==null){
            fileChooser = new JFileChooser();
            choosePGN.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    int returnVal = fileChooser.showOpenDialog(SoloMenu.this);

                    if (returnVal == JFileChooser.APPROVE_OPTION) {
                        PGNFile = fileChooser.getSelectedFile();
                    } else {
                        // Cancel by user. Do nothing.
                    }
                }   
            });
        }
    }


    /**
     * PaintComponent, only for the background.
     */
    @Override
    public void paintComponent(Graphics g){
        g.drawImage(bg, 0, 0, this.getWidth(), this.getHeight(), this);
    }
    
    private void onStartButtonPress(){
        PipedWriter pipedWriter = new PipedWriter();
        PipedReader pipedReader = new PipedReader();
        
        try {
            pipedReader.connect(pipedWriter);
        } catch (IOException ex) {
            assert false : "erreur de connection au pipedWriter";
        }

        //initializing player
        //white
        IChessPlayer whitePlayer = playersSelectPannel.getWhitePlayer();

        //black
        IChessPlayer blackPlayer = playersSelectPannel.getBlackPlayer();

        if (whitePlayer==null || blackPlayer==null)
        {
                JOptionPane.showMessageDialog(
                        SoloMenu.this,
                        "A player could not be set up.",
                        "Error",
                        JOptionPane.INFORMATION_MESSAGE);
        } else {
            // New game without PGN.
            if(gameToStart==null){
                if (PGNFile == null) {
                    System.out.println("New game!");
                    MW.getGameData().startGame(whitePlayer, blackPlayer);
                } else {
                    System.out.println("Loading PGN file...");
                    ChessGame g;
                    try {
                        g = GameData.loadGameFromPGN(new FileReader(PGNFile));
                        MW.getGameData().startGame(whitePlayer, blackPlayer, g);
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(
                                null,
                                "Invalid PGN file.",
                                "Error",
                                JOptionPane.ERROR_MESSAGE);
                    }
                }
            }else{
                MW.getGameData().startGame(
                        whitePlayer,
                        blackPlayer,
                        gameToStart);
            }
        }
    }
}
